const crypto = require('crypto');
const { get } = require('./db'); 
const key = 'kdueiwudhskeowpcgskeudslenxgiwkd';

exports.now = () => parseInt(Date.now() / 1000);

// string, string
exports.encrypt = (k, v) => {
  const text = JSON.stringify({ k, v, t: parseInt(Date.now() / 1000) });
  const iv = crypto.randomBytes(16);
  const cipher = crypto.createCipheriv('aes-256-cfb', key, iv);
  const enc = [iv, cipher.update(text, 'utf8')];

  enc.push(cipher.final());

  return Buffer.concat(enc).toString('hex');
}

// string, string, int
exports.decrypt = (k, c, lifecycle = 0) => {
  const contents = Buffer.from(c, 'hex');
  const iv = contents.slice(0, 16);
  const textBytes = contents.slice(16);
  const decipher = crypto.createDecipheriv('aes-256-cfb', key, iv);
  const res = decipher.update(textBytes, '', 'utf8');
  const o = JSON.parse(res + decipher.final('utf8'));

  if (lifecycle !== 0 && o.t + lifecycle < parseInt(Date.now() / 1000)) return null;
  if (o.k !== k) return null;

  return o.v;
}

exports.door = async (token) => {
  const userid = exports.decrypt('user', token);

  if (!userid) throw new Error('token 无效');

  const user = await get('user', userid);

  if (!user) throw new Error('用户不存在');

  return user;
}

exports.err = message => {
  return {
    err_message: message,
    data: null,
  }
}

exports.ok = data => {
  return {
    err_message: null,
    data,
  }
}

exports.only = require('./only');
